package gruppe7.servlets;

import gruppe7.control.ServletController;
import gruppe7.model.Model;
import gruppe7.model.User;
import gruppe7.util.Html;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class PurchaseTicketServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Html html = new Html();
		PrintWriter out = response.getWriter();
        RequestDispatcher rd = request.getRequestDispatcher("main_links.jsp");
        ServletController sc = ServletController.getInstance();
        User user = sc.getSession(request, response).getUser();

        out.println(html.setHeader("Purchase Ticket"));
        rd.include(request, response);

        out.println("<div id ='content'>");
        out.println("<div id='content-left'>");
        out.println("<h3><img src='images/tickets.png'/> Buy ticket</h3><br/>");
        
        String departure = (String) request.getParameter("departure");
        String destination = (String) request.getParameter("destination");
        float price = Float.parseFloat(request.getParameter("price"));
        
        try {
        	Model model = Model.getInstance();
        	if (model.buyTicket(user, price)) {
        		String msg = 
        			String.format("You are the lucky owner of a ticket from %s to %s, at a price of %d<br/>", departure, destination, new Integer((int) price));
        		
        		out.println(msg);
        		out.println("Your balance is now: " + model.getUserBalance(user));
        	}
        	
        	else {
        		out.println("You need more money!");
        	}
        }
        
        catch (Exception e) {
        	out.println("Database-fejl: " + e);
        }
        
        out.println("</div></div>");
        out.println(html.setFooter());
	}

}
